package cmdGenerate

import (
	"crypto/rand"
	"encoding/json"
	"gdfs-center/socket/codec"
	"math"
	"math/big"
)

// 生成区间[-m, n]的安全随机数
func RangeRand(min, max int64) int64 {
	if min > max {
		panic("the min is greater than max!")
	}

	if min < 0 {
		f64Min := math.Abs(float64(min))
		i64Min := int64(f64Min)
		result, _ := rand.Int(rand.Reader, big.NewInt(max+1+i64Min))

		return result.Int64() - i64Min
	} else {
		result, _ := rand.Int(rand.Reader, big.NewInt(max-min+1))
		return min + result.Int64()
	}
}

//生成生成发送指令
func GenerateSendMsg(cmd int, jsonb []byte) *codec.Response {
	resp := &codec.Response{
		SerialNum: uint64(RangeRand(1, 1025)),
		Cmd:       cmd,
		Data:      jsonb,
	}
	return resp
}

//生成停止全量同步指令
func GenerateStopSyncDataCmd(taskid int64) []byte {
	stop := &codec.StopSyncFullCmd{TaskId: taskid}
	jsonb, _ := json.Marshal(stop)
	return codec.EncoderData(GenerateSendMsg(4, jsonb))
}

//生成创建数据传输tcp指令
func GenerateTcpServer(taskid int64, port int) []byte {
	server := &codec.TranmitServerCmd{
		DbPort: port,
		TaskId: taskid,
	}
	jsonb, _ := json.Marshal(server)
	return codec.EncoderData(GenerateSendMsg(9, jsonb))
}

//生成连接迁移服务器指令
func GenerateConnTcpServer(dbport int, taskid int64, ip string) []byte {
	conn := codec.ConnTcpServerCmd{
		DbPort: dbport,
		TaskId: taskid,
		IP:     ip,
	}
	jsonb, _ := json.Marshal(conn)
	return codec.EncoderData(GenerateSendMsg(7, jsonb))
}

//生成通知绑定或解绑节点指令
func GenerateNotisNode(n codec.NoticeNodeCmd) []byte {
	jsonb, _ := json.Marshal(n)
	return codec.EncoderData(GenerateSendMsg(11, jsonb))
}

//生成TCP关闭通道指令
func GenerateCloseTcptun(taskid int64, storeid, targetid string) []byte {
	closetun := codec.CloseTcpTun{
		TaskId:   taskid,
		TargetId: targetid,
		StoreId:  storeid,
	}
	jsonb, _ := json.Marshal(closetun)
	return codec.EncoderData(GenerateSendMsg(3, jsonb))
}
